$(function () {
  var layer = layui.layer;
  var form = layui.form;
  let img_name = null;

  // var laypage = layui.laypage
  var ggw = {
    page: '1', // 页码值，默认请求第一页的数据
    limit: '10', // 每页显示几条数据，默认每页显示2条
    advimgdesc: '', // 广告图描述
    advimgpos: '', // 广告图所在广告位id
  };

  // 全选框
  $('#img_Allbox').change(function () {
    $('.check').prop('checked', $(this).prop('checked'));
    if ($('#img_Allbox').prop('checked') !== true) {
      $('.shanchu_btn').hide();
    } else {
      $('.shanchu_btn').show();
    }
  });
  $('.check').change(function () {
    if ($('.check:checked').lenght == $('.check').lenght) {
      $('#img_Allbox').prop('checked', true);
    } else {
      $('#img_Allbox').prop('checked', false);
    }
  });

  img_add();
  // 广告图分页渲染
  function img_add() {
    axios({
      method: 'GET',
      url: '/ydd_advimg/list',
      params: ggw,
      headers: {
        'x-token': localStorage.getItem('x-token'),
      },
    }).then(function (res) {
      console.log(res);
      img_name = res.data.data.data;
      console.log(res.data.data.data);
      // 下拉框内容渲染
      // xl_arr(img_name)
      // xl_img = img_name;
      xl_arr(img_name);
      let count = res.data.data.count;
      let curr = res.data.data.currentPage;
      page(count, curr);
      let imgNew_arr = res.data.data.data.map(item => {
        return `
                <tr>
                <td> <input class="check" type="checkbox"></td>
                <td>${item.id}</td>
                <td class="advposname_img">${item.advposname}</td>
                <td class="advimgdesc_img">${item.advimgdesc}</td>
                <td class="advimgsrc_img"> <img src="http://124.223.14.236:8060/${item.advimgsrc}" ></td>
                <td class="advimglink_img">${item.advimglink}</td>
                <th>
                <div class="layui-btn-group">
                <button type="button"  class="layui-btn layui-btn-sm  layui-btn-radius layui-btn-normal" data-id="${item.id}" id="amend";>
                  <i class="layui-icon" >&#xe642;</i>
                </button>
                <button type="button" class="layui-btn layui-btn-sm layui-btn-radius layui-btn-danger btn-delete" data-id="${item.id}">
                  <i class="layui-icon">&#xe640;</i>
                </button>
              </div></th>
              </tr>
                `;
      });
      $('tbody').html(imgNew_arr);
    });
  }
  function page(count, curr) {
    var laypage = layui.laypage;
    //执行一个laypage实例
    laypage.render({
      elem: 'pageBox', //分页容器
      count: count, //数据总数
      limit: 10, //每页总数
      curr: curr, //页数
      // // 定义不同功能
      layout: ['count' /*条数*/, 'limit' /*下拉选页数*/, 'prev' /*上一页*/, 'page' /*每一页*/, 'next' /*下一页*/, 'skip' /*切换分页*/],
      limits: [2, 4, 6, 8, 10],
      // 每次切换不同的页数都会重新执行渲染函数
      jump: (obj, first) => {
        ggw.page = obj.curr;
        ggw.limit = obj.limit;
        if (!first) {
          img_add();
        }
      },
    });
  }

  // 搜索区域=======================
  $('#btn_ss').on('click', function () {
    // // 获取表单中选中项的值
    console.log(12);
    var advimgdesc = $('[name=advimgdesc]').val();
    var advimgpos = $('[name=advimgpos]').val();
    // // 为查询参数对象 q 中对应的属性赋值
    ggw.advimgdesc = advimgdesc;
    ggw.advimgpos = advimgpos;
    // // 根据最新的筛选条件，重新渲染表格的数据
    img_add();
  });
  // 重置===================
  $('#btn_cz').on('click', function () {
    img_add();
    $('.sousuo').val('');
  });

  // 广告图删除
  $('tbody').on('click', '.btn-delete', function () {
    let id = $(this).attr('data-id');
    let len = $('.btn-delete').length;
    console.log(id);
    layer.confirm('确定删除吗,是否继续?', { icon: 3, title: '提示' }, function (index) {
      axios({
        method: 'GET',
        url: '/ydd_advimg/del',
        params: {
          id: id,
        },
        headers: {
          'x-token': localStorage.getItem('x-token'),
        },
      }).then(function (res) {
        console.log(res);
        if (res.status !== 200) {
          return layer.msg('删除失败');
        }
        layer.msg('删除成功');
        if (len === 1) {
          ggw.page = ggw.page = 1 ? 1 : ggw.page - 1;
        }
        img_add();
      });
      layer.close(index);
    });
  });

  // 广告图修改
  let amend = null;
  let id_amend;
  $('tbody').on('click', '#amend', function () {
    id_amend = $(this).attr('data-id');
    console.log(id_amend);
    amend = layer.open({
      type: 1,
      title: '修改广告位',
      content: $('#dialog-amend').html(),
      area: ['800px', '400px'],
    });
    $('#city').html(new_xl_arr);
    form.render();

    // 点击修改获得当前表格里内容
    axios({
      method: 'GET',
      url: '/ydd_advimg/rowInfo',
      params: {
        id: id_amend,
      },
      headers: {
        'x-token': localStorage.getItem('x-token'),
      },
    }).then(function (res) {
      res_data = res.data.data.advimgpos;
      console.log(res_data);
      form.val('form-edit', res.data.data);
    });
  });

  // 点击上传弹出文件
  $('body').on('click', '.shangchuan', function () {
    $('#file').click();
  });

  // 下拉框渲染
  let new_xl_arr = null;
  function xl_arr(arr) {
    console.log(arr);
    new_xl_arr = arr.map(item => {
      return `
         <option value="${item.advimgpos}">${item.advposname}</option>`;
    });
    console.log(new_xl_arr);
    // let newArr = new_xl_arr.filter(item.value ===)
    new_xl_arr.unshift(' <option value="">请选择内容</option>');
    $('#city_one').html(new_xl_arr);
    form.render();
  }

  // 图片
  $('body').on('change', '#file', function (e) {
    $('#form2').submit();
  });

  let img = null;
  $('body').on('submit', '#form2', e => {
    console.log(1212);
    e.preventDefault();
    let fd = new FormData($('#form2')[0]);
    $.ajax({
      url: 'http://124.223.14.236:8060/admin/common/upload?type=images',
      method: 'POST',
      data: fd,
      headers: {
        'x-token': localStorage.getItem('x-token'),
      },
      // 注意：formData格式的请求要加上下面两项配置
      contentType: false,
      processData: false,
      success: function (res) {
        console.log(res);
        img = res.data.savePath;
      },
    });
  });

  // 修改渲染
  $('body').on('submit', '#form-amend', function (e) {
    e.preventDefault();
    // let img_q = $(this).serialize()
    let advimgdesc = $('#advimgdesc_amend').val();
    let advimglink = $('[name=advimglink]').val();
    let advimgpos = $('#city').val();
    console.log(advimgdesc);
    axios({
      method: 'POST',
      url: '/ydd_advimg/update',
      data: {
        advimgpos: advimgpos,
        advimgdesc: advimgdesc,
        advimglink: advimglink,
        advimgsrc: img,
        id: id_amend,
      },
      headers: {
        'x-token': localStorage.getItem('x-token'),
      },
    }).then(function (res) {
      console.log(res);
      if (res.status !== 200) {
        return layer.msg('修改失败');
      }
      layer.msg('修改成功');
      img_add();
      layer.close(amend);
    });
  });
  // 取消按钮
  $('body').on('click', '.quxiao', function () {
    layer.close(amend);
  });
  // 添加
  $('.zengjia').on('click', function () {
    amend = layer.open({
      type: 1,
      title: '新增广告位',
      content: $('#dialog-add').html(),
      area: ['800px', '400px'],
    });
    $('#city').html(new_xl_arr);
    form.render();
  });

  // 添加渲染
  $('body').on('submit', '#form-add', function (e) {
    e.preventDefault();
    // console.log($(this).serialize());
    let advimgdesc = $('#advposdesc').val();
    let advimglink = $('#advimglink').val();
    let advimgpos = $('#city').val();
    console.log(advimgdesc);
    console.log(advimglink);
    axios({
      method: 'POST',
      url: '/ydd_advimg/add',
      data: {
        advimgdesc: advimgdesc,
        advimglink: advimglink,
        advimgpos: advimgpos,
        advimgsrc: img,
      },
      headers: {
        'x-token': localStorage.getItem('x-token'),
      },
    }).then(function (res) {
      console.log(res);
      if (res.status !== 200) {
        return layer.msg('添加失败');
      }
      layer.msg('添加成功');
      img_add();
      layer.close(amend);
    });
  });

  // 全选删除
  $('.shanchu_btn').on('click', function () {
    $('table').html('<tr><th>#</th><th class="advposname_yc">广告位名称</th><th class="advposdesc_yc">广告位描述</th><th class="default_data_yc">广告图数量</th><th class="advpossize_yc">广告位尺寸</th><th style="text-align: center">操作</th></tr>');
    $('#foot').show();
    $('#pageBox').hide();
  });
  $('#export').click(function (e) {
    var table = $('.layui-table');
    var preserveColors = table.hasClass('table2excel_with_colors') ? true : false;
    $(table).table2excel({
      exclude: '.noExl',
      name: 'Excel Document Name',
      filename: 'myFileName' + new Date().toISOString().replace(/[\-\:\.]/g, '') + '.xls',
      fileext: '.xls',
      exclude_img: true,
      exclude_links: true,
      exclude_inputs: true,
      preserveColors: preserveColors,
    });
  });

  // 右上角按钮
  let a = true;
  $('.rigth_one').on('click', function () {
    if (a) {
      $('#adv_ss').hide();
      $(this).css('transform', 'rotate(180deg)');
      a = false;
      return;
    }
    console.log(12);
    $('#adv_ss').show();
    $(this).css('transform', 'rotate(360deg)');
    a = true;
  });

  // =====================
  let b = true;
  $('.layui-icon-app').on('click', function () {
    if (b) {
      $('.adv-box').show();
      b = false;
    } else {
      $('.adv-box').hide();
      b = true;
    }
  });

  $('.layui-icon-refresh-3').on('click', function () {
    $('.sousuo').val('');
    img_add();
  });
  $('.check_img').prop('checked', true);
  let btns = document.querySelectorAll('.check_img');
  console.log(btns.length);
  for (let i = 0; i < btns.length; i++) {
    btns[i].setAttribute('index', i);
    btns[i].onclick = function () {
      index = this.getAttribute('index');
      console.log(index);
      if (index == 0) {
        $('.advposname_img').toggleClass('all');
      } else if (index == 1) {
        $('.advimgdesc_img').toggleClass('all');
      } else if (index == 2) {
        $('.advimgsrc_img').toggleClass('all');
      } else if (index == 3) {
        $('.advimglink_img').toggleClass('all');
      }
    };
  }
});
